/**
 * 长轮询
 * @param getData 获取数据的函数
 * @param delay 获取失败后，延迟重试的时间，单位ms
 */

interface IlongPolling {
  promise: Promise<any>
  onLongPolling: () => void
  offLongPolling: () => void
}

const longPolling = (
  getData: () => Promise<void> = () => Promise.resolve(),
  delay: number = 5 * 1000,
): IlongPolling => {
  const { promise, resolve, reject } = Promise.withResolvers()

  let isUnlongPollingd: boolean | null = false

  // 轮询方法
  const recursivelongPolling = async () => {
    if (isUnlongPollingd) return

    try {
      await getData()
      await new Promise((resolve) => setTimeout(resolve, delay))
      recursivelongPolling()
      resolve('success')
    } catch (error) {
      await new Promise((resolve) => setTimeout(resolve, delay))
      recursivelongPolling()
      reject(error)
    }
  }

  // 开启轮询
  const onLongPolling = () => {
    if (isUnlongPollingd) {
      isUnlongPollingd = false
      recursivelongPolling()
    }
  }

  // 停止轮询
  const offLongPolling = () => {
    isUnlongPollingd = true
  }

  // 初始化轮询
  recursivelongPolling()

  return { promise, onLongPolling, offLongPolling }
}

export default longPolling

// 使用方式：
// import longPolling from "~utils/longPolling" // 导入轮询

// let pollingInstance = null // 定义轮询实例

// pollingInstance = longPolling(getQRCodeState, 2000) // 开启轮询

// pollingInstance?.offLongPolling() // 停止轮询

// pollingInstance = null // 清除轮询实例

